package com.twobu.twobuinsight.controller;

import com.twobu.twobuinsight.annotation.RateLimit;
import com.twobu.twobuinsight.common.Result;
import com.twobu.twobuinsight.config.ExternalApiConfig;
import com.twobu.twobuinsight.dto.TaskOutcomeResponse;
import com.twobu.twobuinsight.dto.TaskStatusListResponse;
import com.twobu.twobuinsight.dto.TaskSubmitRequest;
import com.twobu.twobuinsight.dto.TaskSubmitResponse;
import com.twobu.twobuinsight.dto.TaskPDFResponse;
import com.twobu.twobuinsight.dto.TaskWebpageResponse;
import com.twobu.twobuinsight.service.AIResearchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/task")
@Tag(name = "AI研究平台", description = "AI研究平台相关接口")
@Deprecated
public class AIResearchController {

    @Autowired
    private AIResearchService aiResearchService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ExternalApiConfig apiConfig;

    @PostMapping("/submit")
    @Operation(summary = "提交研究任务")
    @RateLimit(count = 1, timeUnit = TimeUnit.SECONDS,timeValue = 10,description = "提交任务可能较为耗时，请勿频繁调用")
    public Result<TaskSubmitResponse> submitTask(@RequestBody TaskSubmitRequest request) {
        log.info("接收到研究任务提交请求: {}", request);
        try {
            // 调用服务层提交任务
            TaskSubmitResponse response = aiResearchService.submitTask(request);
            log.info("研究任务提交成功: {}", response);
            return Result.success(response);
        } catch (Exception e) {
            log.error("研究任务提交失败", e);
            return Result.error("研究任务提交失败: " + e.getMessage());
        }
    }

    @GetMapping("/outcome")
    @Operation(summary = "获取任务结果")
    @RateLimit(count = 10, timeUnit = TimeUnit.SECONDS,timeValue = 10)
    public Result<TaskOutcomeResponse> getTaskOutcome(@RequestParam String taskId) {
        log.info("接收到获取任务结果请求, taskId: {}", taskId);
        try {
            // 调用服务层获取任务结果
            TaskOutcomeResponse response = aiResearchService.getTaskOutcome(taskId);
            log.info("获取任务结果成功, taskId: {}", taskId);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取任务结果失败, taskId: {}", taskId, e);
            return Result.error("获取任务结果失败: " + e.getMessage());
        }
    }


    @GetMapping("/status")
    @Operation(summary = "获取任务状态")
    public Result<TaskStatusListResponse> getTaskStatus(@RequestParam String taskId) {
        log.info("接收到获取任务状态请求, taskId: {}", taskId);
        try {
            // 调用服务层获取任务状态
            TaskStatusListResponse response = aiResearchService.getTaskStatus(taskId);
            log.info("获取任务状态成功, taskId: {}", taskId);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取任务状态失败, taskId: {}", taskId, e);
            return Result.error("获取任务状态失败: " + e.getMessage());
        }
    }

    @PostMapping("/accept")
    @Operation(summary = "接收任务结果更新")
    public Result<Void> acceptTaskOutcome(@RequestBody TaskOutcomeResponse taskOutcome) {
        log.info("接收到任务结果更新, taskId: {}", taskOutcome != null ? taskOutcome.getTaskId() : null);
        try {
            // 调用服务层处理任务结果更新
            aiResearchService.acceptTaskOutcome(taskOutcome);
            log.info("处理任务结果更新成功");
            return Result.success(null);
        } catch (Exception e) {
            log.error("处理任务结果更新失败", e);
            return Result.error("处理任务结果更新失败: " + e.getMessage());
        }
    }

    @GetMapping("/pdf/{taskId}")
    @Operation(summary = "生成任务PDF报告")
    public Result<TaskPDFResponse> generateTaskPDF(@PathVariable String taskId) {
        log.info("接收到生成任务PDF报告请求, taskId: {}", taskId);
        try {
            // 调用服务层生成PDF
            TaskPDFResponse response = aiResearchService.generateTaskPDF(taskId);
            log.info("生成任务PDF报告成功, taskId: {}", taskId);
            return Result.success(response);
        } catch (Exception e) {
            log.error("生成任务PDF报告失败, taskId: {}", taskId, e);
            return Result.error("生成任务PDF报告失败: " + e.getMessage());
        }
    }

    @GetMapping("/pdf/download/{taskId}")
    @Operation(summary = "下载任务PDF报告")
    public ResponseEntity<byte[]> downloadTaskPDF(@PathVariable String taskId, HttpServletResponse response) {
        log.info("接收到下载任务PDF报告请求, taskId: {}", taskId);
        try {
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            headers.set("Accept", "application/json");

            // 如果有API密钥，添加到请求头
            if (apiConfig.getApiKey() != null && !apiConfig.getApiKey().isEmpty()) {
                headers.set("X-API-Key", apiConfig.getApiKey());
            }

            // 构建请求实体
            HttpEntity<?> requestEntity = new HttpEntity<>(headers);

            // 构建完整URL
            String url = apiConfig.getBaseUrl() + apiConfig.getTaskPdfDownloadPath() + "/" + taskId;
            log.info("调用外部API下载PDF: {}", url);

            // 发送请求获取PDF文件
            ResponseEntity<byte[]> pdfResponse = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    requestEntity,
                    byte[].class
            );

            // 设置响应头
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.APPLICATION_PDF);
            responseHeaders.setContentDisposition(ContentDisposition.attachment()
                    .filename("task-report-" + taskId + ".pdf")
                    .build());

            // 返回PDF文件
            return new ResponseEntity<>(pdfResponse.getBody(), responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            log.error("下载任务PDF报告失败, taskId: {}", taskId, e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }
    }

    @GetMapping("/webpage/generate")
    @Operation(summary = "生成任务网页报告")
    @RateLimit(count = 1, timeUnit = TimeUnit.SECONDS,timeValue = 5,description = "生成网页可能较为耗时，请勿频繁调用")
    public Result<TaskWebpageResponse> generateTaskWebpage(
            @RequestParam String taskId,
            @RequestParam(required = false, defaultValue = "false") boolean regenerate) {
        log.info("接收到生成任务网页报告请求, taskId: {}, regenerate: {}", taskId, regenerate);
        try {
            // 调用服务层生成网页，传入regenerate参数
            TaskWebpageResponse response = aiResearchService.generateTaskWebpage(taskId, regenerate);
            log.info("生成任务网页报告成功, taskId: {}", taskId);
            return Result.success(response);
        } catch (Exception e) {
            log.error("生成任务网页报告失败, taskId: {}", taskId, e);
            return Result.error("生成任务网页报告失败: " + e.getMessage());
        }
    }
}
